package org.oradoc.utils.freemarker;

/**
 * Class responsible for calculating the location of elements when they are
 * displayed into an HTML table.
 *
 * @author Vladimir Ritz Bossicard
 */
public class HtmlTableOrganizer {

    /** number of columns */
    private int columns;
    /** minimal number of rows */
    private int minrows;
    /** maximal number of elements */
    private int maxelements;

    public HtmlTableOrganizer(final int elements, final int columns) {
        this.columns = columns;
        this.maxelements = calculateMax(elements);
        this.minrows = (int) Math.ceil((double) this.maxelements / (double) columns);
    }

    /**
     * Returns the table's size.
     * @return index (starting from 0)
     */
    public int getTableSize() {
        return this.maxelements;
    }

    /**
     * Returns the maximal size of the HTML table.
     *
     * @param size number of elements
     * @return
     */
    private int calculateMax(final int elements) {
        if (elements % this.columns == 0) {
            return elements;
        }
        return elements + (this.columns - (elements % this.columns));
    }

    /**
     * Calculates the final position of the given element.
     * @param pos position [0..maxsize] of the element
     * @return an index [0..maxsize]
     */
    public int calculatePosition(final int pos) {
        int col = (int) Math.floor((double) pos / (double) this.minrows);
        int row = pos % this.minrows;

        // System.out.println(element + ": " + col + " " + row);

        return col + (row * this.columns);
    }

}
